package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lych.commons.utils.Constants;
import com.lych.commons.utils.JwtUtils;
import com.lych.model.domain.Admin;
import com.lych.model.vo.AdminVo;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录
     * @param map
     * @return
     */
    public Map login(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");

        //用户名密码非空判断
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            Map map1 = new HashMap();
            map1.put("message","用户名或密码为空");
            return map1;
        }

        //验证码非空判断
        if (StringUtils.isEmpty(verificationCode)){
            throw new BusinessException("验证码为空");
        }

        //判断验证码是否正确
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(Constants.CAP_CODE + uuid);

        //根据用户名查询用户
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(lqw);
        //判断用户名是否存在，密码是否错误
        String md5 = SecureUtil.md5(password);
        if (admin == null || !admin.getPassword().equals(md5)) {
            throw new BusinessException("账号或密码错误错误");
        }

        //生成token
        Map<String,Object> cliais = new HashMap<>();
        cliais.put("username",username);
        cliais.put("id",admin.getId());
        String token = JwtUtils.getToken(cliais);
        //构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    /**
     * 用户基本信息
     * @return
     */
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);
    }
}
